package com.zy.facepp.service;

import java.util.ArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.zy.facepp.bean.BaseParams;
import com.zy.facepp.bean.FaceppConfig;
import com.zy.facepp.constant.FaceppConstant;
import com.zy.facepp.domain.TblFaceppReqLog;
import com.zy.facepp.repository.TblFaceppReqLogRepository;

/**
 * Face++ Service
 *
 * @author zhanghengchang
 * @date 2018/3/8
 */
@Service
public class FacePlusPlusService {

    private static Logger logger = LoggerFactory.getLogger(FacePlusPlusService.class);

    @Autowired
    protected FaceppConfig faceppConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TblFaceppReqLogRepository tblCardReqLogRepository;

    /**
     * face++请求通用方法
     *
     * @param apiUrl API URL
     * @param mvMap Map
     * @return 识别结果
     */
    protected JSONObject postTo(String apiUrl, MultiValueMap<String, Object> mvMap) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, Object>> requestEntity
            = new HttpEntity<MultiValueMap<String, Object>>(mvMap, headers);

        ResponseEntity<JSONObject> resp = null;
        try {
            resp = restTemplate.postForEntity(apiUrl, requestEntity, JSONObject.class);
        } catch (Exception e) {
            JSONObject errorJson = new JSONObject();
            errorJson.put(FaceppConstant.CONST_RESULT_SUCCESS, false);
            errorJson.put(FaceppConstant.CONST_RESULT_ERROR_MESSAGE, e.getMessage());
            return errorJson;
        }

        return resp.getBody();
    }

    /**
     * 记录请求，返回信息
     *
     * @param apiType 卡片类别
     * @param reqInfo 请求信息
     * @param respInfo 返回信息
     */
    protected void writeReqLog(String apiType, BaseParams reqInfo, JSONObject respInfo) {

        TblFaceppReqLog tblReqLog = new TblFaceppReqLog();
        tblReqLog.setRequestId(reqInfo.getRequestId());
        tblReqLog.setApiType(apiType);
        tblReqLog.setReqInfo(JSONObject.toJSONString(reqInfo));
        tblReqLog.setRespInfo(respInfo.toString());

        tblCardReqLogRepository.save(tblReqLog);
    }

    /**
     * 编辑返回数据，便于返回调用方后数据操作
     *
     * @param apiType API类型
     * @param params 调用参数
     * @param json 接口返回数据
     * @return 编辑后的返回数据
     */
    protected JSONObject editResponse(String apiType, BaseParams params, JSONObject json) {
        // 设定为调用方的request id
        json.put(FaceppConstant.CONST_REQUEST_ID, params.getRequestId());

        // 判断是否成功
        Object error = json.get(FaceppConstant.CONST_RESULT_ERROR_MESSAGE);

        boolean isSuccess = true;
        if (FaceppConstant.CONST_TYPE_IDCARD.equals(apiType) || FaceppConstant.CONST_TYPE_DRIVER_LICENSE.equals(apiType)
            || FaceppConstant.CONST_TYPE_VEHICLE_LICENSE.equals(apiType)) {
            Object cards = json.get(FaceppConstant.CONST_CONTENT_CARD);
            if (cards == null) {
                isSuccess = false;
            } else {
                int cardInfoSize = ((ArrayList<JSONObject>)cards).size();
                isSuccess = (cardInfoSize > 0);
            }
        } else if (FaceppConstant.CONST_TYPE_BANK_CARD.equals(apiType)) {
            Object cards = json.get(FaceppConstant.CONST_CONTENT_BANK_CARD);
            if (cards == null) {
                isSuccess = false;
            } else {
                int cardInfoSize = ((ArrayList<JSONObject>)cards).size();
                isSuccess = (cardInfoSize > 0);
            }
        } else if (FaceppConstant.CONST_TYPE_COMPARE.equals(apiType)) {
            Object confidence = json.get(FaceppConstant.KEY_FOR_CONFIDENCE);
            if (confidence == null) {
                isSuccess = false;
            }
        }

        if (error == null && isSuccess) {
            json.put(FaceppConstant.CONST_RESULT_SUCCESS, true);
        } else {
            json.put(FaceppConstant.CONST_RESULT_SUCCESS, false);
        }

        return json;
    }
}
